"""
校园圈子模型
包含二手市场、恋爱交友、打听求助、发布兼职、校园八卦等功能
"""

from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone

User = get_user_model()


class Category(models.Model):
    """
    帖子分类模型
    用于对帖子进行分类管理
    """
    
    name = models.CharField(
        max_length=50,
        unique=True,
        verbose_name='分类名称'
    )
    
    description = models.TextField(
        blank=True,
        verbose_name='分类描述'
    )
    
    # 分类图标
    icon = models.CharField(
        max_length=50,
        blank=True,
        verbose_name='分类图标'
    )
    
    # 排序权重
    order = models.IntegerField(
        default=0,
        verbose_name='排序权重'
    )
    
    # 是否启用
    is_active = models.BooleanField(
        default=True,
        verbose_name='是否启用'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    class Meta:
        verbose_name = '帖子分类'
        verbose_name_plural = '帖子分类'
        db_table = 'circle_categories'
        ordering = ['order', 'name']
    
    def __str__(self):
        return self.name


class Post(models.Model):
    """
    帖子模型
    校园圈子的核心内容
    """
    
    # 帖子类型选择
    POST_TYPE_CHOICES = [
        ('second_hand', '二手市场'),
        ('dating', '恋爱交友'),
        ('help', '打听求助'),
        ('job', '发布兼职'),
        ('gossip', '校园八卦'),
        ('other', '其他'),
    ]
    
    # 帖子状态选择
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('published', '已发布'),
        ('hidden', '已隐藏'),
        ('deleted', '已删除'),
    ]
    
    # 基础信息
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='posts',
        verbose_name='作者'
    )
    
    category = models.ForeignKey(
        Category,
        on_delete=models.CASCADE,
        related_name='posts',
        verbose_name='分类'
    )
    
    post_type = models.CharField(
        max_length=20,
        choices=POST_TYPE_CHOICES,
        verbose_name='帖子类型'
    )
    
    title = models.CharField(
        max_length=200,
        verbose_name='标题'
    )
    
    content = models.TextField(
        verbose_name='内容'
    )
    
    # 状态信息
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='published',
        verbose_name='状态'
    )
    
    # 统计信息
    view_count = models.IntegerField(
        default=0,
        verbose_name='浏览次数'
    )
    
    like_count = models.IntegerField(
        default=0,
        verbose_name='点赞数'
    )
    
    comment_count = models.IntegerField(
        default=0,
        verbose_name='评论数'
    )
    
    # 特殊功能
    is_top = models.BooleanField(
        default=False,
        verbose_name='是否置顶'
    )
    
    is_essence = models.BooleanField(
        default=False,
        verbose_name='是否精华'
    )
    
    allow_comment = models.BooleanField(
        default=True,
        verbose_name='是否允许评论'
    )
    
    # 时间信息
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '帖子'
        verbose_name_plural = '帖子'
        db_table = 'circle_posts'
        ordering = ['-is_top', '-created_at']
    
    def __str__(self):
        return self.title
    
    @property
    def tags(self):
        """获取帖子的标签"""
        return [post_tag.tag for post_tag in self.post_tags.all()]


class PostImage(models.Model):
    """
    帖子图片模型
    存储帖子相关的图片
    """
    
    post = models.ForeignKey(
        Post,
        on_delete=models.CASCADE,
        related_name='images',
        verbose_name='帖子'
    )
    
    image = models.ImageField(
        upload_to='post_images/',
        verbose_name='图片'
    )
    
    order = models.IntegerField(
        default=0,
        verbose_name='排序'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='上传时间'
    )
    
    class Meta:
        verbose_name = '帖子图片'
        verbose_name_plural = '帖子图片'
        db_table = 'circle_post_images'
        ordering = ['order', 'created_at']
    
    def __str__(self):
        return f"{self.post.title} - 图片{self.order}"


class Comment(models.Model):
    """
    评论模型
    存储帖子的评论信息
    """
    
    post = models.ForeignKey(
        Post,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name='帖子'
    )
    
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name='评论者'
    )
    
    # 支持回复功能
    parent = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='replies',
        verbose_name='父评论'
    )
    
    content = models.TextField(
        verbose_name='评论内容'
    )
    
    # 统计信息
    like_count = models.IntegerField(
        default=0,
        verbose_name='点赞数'
    )
    
    # 状态信息
    is_hidden = models.BooleanField(
        default=False,
        verbose_name='是否隐藏'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='评论时间'
    )
    
    class Meta:
        verbose_name = '评论'
        verbose_name_plural = '评论'
        db_table = 'circle_comments'
        ordering = ['created_at']
    
    def __str__(self):
        return f"{self.author.username} 评论了 {self.post.title}"


class Like(models.Model):
    """
    点赞模型
    记录用户对帖子和评论的点赞
    """
    
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='likes',
        verbose_name='用户'
    )
    
    # 支持对帖子和评论点赞
    post = models.ForeignKey(
        Post,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='likes',
        verbose_name='帖子'
    )
    
    comment = models.ForeignKey(
        Comment,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='likes',
        verbose_name='评论'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='点赞时间'
    )
    
    class Meta:
        verbose_name = '点赞'
        verbose_name_plural = '点赞'
        db_table = 'circle_likes'
        unique_together = [
            ('user', 'post'),  # 用户对同一帖子只能点赞一次
            ('user', 'comment'),  # 用户对同一评论只能点赞一次
        ]
    
    def __str__(self):
        if self.post:
            return f"{self.user.username} 点赞了 {self.post.title}"
        else:
            return f"{self.user.username} 点赞了评论"


class Tag(models.Model):
    """
    标签模型
    用于给帖子添加标签
    """
    
    name = models.CharField(
        max_length=50,
        unique=True,
        verbose_name='标签名称'
    )
    
    color = models.CharField(
        max_length=7,
        default='#007bff',
        verbose_name='标签颜色'
    )
    
    use_count = models.IntegerField(
        default=0,
        verbose_name='使用次数'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    class Meta:
        verbose_name = '标签'
        verbose_name_plural = '标签'
        db_table = 'circle_tags'
        ordering = ['-use_count', 'name']
    
    def __str__(self):
        return self.name


class PostTag(models.Model):
    """
    帖子标签关联模型
    用于关联帖子和标签
    """
    
    post = models.ForeignKey(
        Post,
        on_delete=models.CASCADE,
        related_name='post_tags',
        verbose_name='帖子'
    )
    
    tag = models.ForeignKey(
        Tag,
        on_delete=models.CASCADE,
        related_name='post_tags',
        verbose_name='标签'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='关联时间'
    )
    
    class Meta:
        verbose_name = '帖子标签关联'
        verbose_name_plural = '帖子标签关联'
        db_table = 'circle_post_tags'
        unique_together = ['post', 'tag']
    
    def __str__(self):
        return f"{self.post.title} - {self.tag.name}"
